/*
 * @Author: chengjiang
 * @Date: 2025-07-25 23:29:21
 * @Description:
 */
package server

import (
	"fmt"
	"sync/atomic"

	"github.com/hashicorp/consul/api"
)

type ConsulService struct {
	client        *api.Client
	roundRobinIdx uint64
}

func NewConsulService(addr string) *ConsulService {
	client, err := api.NewClient(&api.Config{Address: addr, Scheme: "http"})
	if err != nil {
		panic(fmt.Sprintf("连接Consul失败: %v", err))
	}
	return &ConsulService{client: client}
}

// 获取服务实例（轮询负载均衡）
func (s *ConsulService) GetInstance(serviceName string) (string, error) {
	services, _, err := s.client.Health().Service(serviceName, "http", false, nil)
	if err != nil || len(services) == 0 {
		return "", fmt.Errorf("服务 %s 无可用实例", serviceName)
	}
	// 轮询算法
	idx := atomic.AddUint64(&s.roundRobinIdx, 1) - 1
	fmt.Println("轮询算法", idx, idx%uint64(len(services)))
	instance := services[idx%uint64(len(services))].Service
	return fmt.Sprintf("http://%s:%d", instance.Address, instance.Port), nil
}